package com.pingan.haofang.searchcloud.quartz.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pingan.haofang.searchcloud.quartz.constants.QuartzConstants;
import com.pingan.haofang.searchcloud.quartz.dto.ScheduleTask;
import com.pingan.haofang.searchcloud.quartz.utils.SpringContextUtil;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;

import static com.pingan.haofang.searchcloud.index.constants.IndexBuildConstants.ARGS;
import static com.pingan.haofang.searchcloud.index.constants.IndexBuildConstants.IS_MANUAL_JOB;
import static com.pingan.haofang.searchcloud.index.constants.IndexBuildConstants.MANUAL_JOB;


/*
 * @author EX-SUNBIXIAO001
 * @date 2018/6/5
 * @since 1.0.0
 */

public class SchduleQuartzJobBean extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(SchduleQuartzJobBean.class);

    private static Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    @Override
    protected void executeInternal(JobExecutionContext context) {
        try {

            String argsStr = context.getMergedJobDataMap().getString(ARGS);
            ScheduleTask task = GSON.fromJson(argsStr, ScheduleTask.class);

            final String manualJob = context.getMergedJobDataMap().getString(MANUAL_JOB);

            //删除JobDataMap中的MANUAL_JOB
            context.getTrigger().getJobDataMap().remove(MANUAL_JOB);
            context.getMergedJobDataMap().remove(MANUAL_JOB);


            final long progressId;
            if (IS_MANUAL_JOB.equals(manualJob)) {
                progressId = task.getArgs().getProgressId();
            } else {
                progressId = 0L;
            }

            Object otargetObject = SpringContextUtil.getBean(task.getTarget());
            Method[] methods = otargetObject.getClass().getMethods();
            for (Method method : methods) {
                //全量，传递全部数据源列表
                if (method.getName().equals(task.getMethod()) && QuartzConstants.FULL_METHOD.equals(task.getMethod())) {
                    method.invoke(otargetObject, task, progressId, task.getArgs().getIndexDatasourceList(), context);
                    break;
                }

                //增量，传递整个参数
                if (method.getName().equals(task.getMethod()) && QuartzConstants.INC_METHOD.equals(task.getMethod())) {
                    method.invoke(otargetObject, task, progressId, task.getArgs(), context);
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("schduleQuartzJobBean execute error >>>>>>", e);
        }
    }


}
